package com.sky.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.dto.OrdersPaymentDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.*;
import com.sky.properties.BaiduProperties;
import com.sky.result.PageResult;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import com.sky.vo.OrderVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;


@Slf4j
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private WeChatPayUtil weChatPayUtil;

    @Autowired
    private BaiduProperties baiduProperties;

    /**
     * 用户下单
     *
     * @param ordersSubmitDTO
     * @return
     */
    @Transactional  //0.开启事务
    @Override
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
        /**
         * 优化配送范围
         */
        String url = "https://api.map.baidu.com/geocoding/v3/?address="+baiduProperties.getShopAddress()+"&output=json&ak="+baiduProperties.getAk()+"&callback=showLocation";

        String shop = HttpClientUtil.doGet(url, null);


        shop = shop.replaceAll("showLocation&&showLocation\\(","");
        shop = shop.replaceAll("\\)","");

        log.info("经纬度：{}",shop);

        JSONObject jsonObject = JSON.parseObject(shop);

        log.info("jsonObject:{}",jsonObject);

        JSONObject jsonObject1 = (JSONObject) (((JSONObject) jsonObject.get("result")).get("location"));

        BigDecimal bigDecimalLng = (BigDecimal) jsonObject1.get("lng");

        double shopLng = bigDecimalLng.setScale(6,BigDecimal.ROUND_DOWN).doubleValue();
        log.info("商家的经度值:{}",shopLng);

        BigDecimal bigDecimalLat = (BigDecimal) jsonObject1.get("lat");
        double shopLat = bigDecimalLat.setScale(6,BigDecimal.ROUND_DOWN).doubleValue();
        log.info("商家的纬度值:{}",shopLat);



        AddressBook address= addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());

        log.info("用户地址簿：{}",address);
        String userAddress = address.getProvinceName() + address.getCityName() + address.getDistrictName() + address.getDetail();
        log.info("用户准确地址:{}",userAddress);

        String userUrl = "https://api.map.baidu.com/geocoding/v3/?address="+userAddress+"&output=json&ak="+baiduProperties.getAk()+"&callback=showLocation";
        String users = HttpClientUtil.doGet(userUrl, null);


        users = users.replaceAll("showLocation&&showLocation\\(","");
        users = users.replaceAll("\\)","");

        log.info("经纬度：{}",users);

        JSONObject jsonObject3 = JSON.parseObject(users);

        log.info("jsonObject:{}",jsonObject);

        JSONObject jsonObject4 = (JSONObject) (((JSONObject) jsonObject3.get("result")).get("location"));

        BigDecimal bigDecimalLng2 = (BigDecimal) jsonObject4.get("lng");
        double userLng = bigDecimalLng2.setScale(6,BigDecimal.ROUND_DOWN).doubleValue();
        log.info("用户经度值:{}",userLng);

        BigDecimal bigDecimalLat2 = (BigDecimal) jsonObject4.get("lat");
        double userLat = bigDecimalLat2.setScale(6,BigDecimal.ROUND_DOWN).doubleValue();
        log.info("用户纬度值:{}",userLat);

        String directionliteUrl = "https://api.map.baidu.com/directionlite/v1/riding?origin="+shopLat+","+shopLng+"&destination="+userLat+","+userLng+"&ak="+baiduProperties.getAk()+"&riding_type=1";

        String riding = HttpClientUtil.doGet(directionliteUrl, null);

        log.info("路线规划：{}",riding);

        JSONObject result = (JSONObject) (JSON.parseObject(riding)).get("result");
        JSONArray routes = (JSONArray) result.get("routes");

        log.info("路线距离：{},",routes);
        log.info("routes类型：{},",routes.getClass().getSimpleName());

        JSONObject jsonObject2 = routes.getJSONObject(0);

        Integer distance = (Integer) jsonObject2.get("distance");

        log.info("具体路线多少米：{}",distance);

        if(distance>5000){
            throw new OrderBusinessException(MessageConstant.EXCEEDING_DELIVERY_DISTANCE);
        }




        // 查询地址表，获取手机号、收货人、收货地址
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            throw new OrderBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        // 查询用户表，获取下单人姓名
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new OrderBusinessException(MessageConstant.USER_NOT_LOGIN);
        }

        // 查询当前用户的购物车
        List<ShoppingCart> cartList = shoppingCartMapper.list(userId);
        if (cartList == null || cartList.size() == 0) {
            throw new OrderBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        // 构造订单对象，将数据新增到orders表中
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        orders.setNumber(UUID.randomUUID().toString()); //订单号
        orders.setStatus(Orders.PENDING_PAYMENT);       //订单状态  1待付款 2待接单 3已接单 4派送中 5已完成 6已取消 7退款
        orders.setUserId(userId);                       //设置用户id
        orders.setOrderTime(LocalDateTime.now());       //下单时间
        orders.setPayStatus(Orders.UN_PAID);            //支付状态 0未支付 1已支付 2退款
        orders.setPhone(addressBook.getPhone());        //手机号
        orders.setAddress(addressBook.getDetail());     //详细地址
        orders.setConsignee(addressBook.getConsignee());//收货人
        orders.setUserName(user.getName());             //下单人
        orderMapper.insert(orders);

        // 构造订单明细对象列表，将数据新增到order_detail表中
        List<OrderDetail> orderDetailList = new ArrayList<>();
        // 将购物车中的商品数据，拷贝到明细对象数据中
        for (ShoppingCart shoppingCart : cartList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart, orderDetail, "id");
            //绑定订单id
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);
        }
        // 批量插入订单明细数据
        orderDetailMapper.insertBatch(orderDetailList);

        // 清空购物车
        shoppingCartMapper.delete(userId);

        // 构造OrderSubmitVO对象，并返回
        return OrderSubmitVO.builder()
                .id(orders.getId())
                .orderNumber(orders.getNumber())
                .orderTime(orders.getOrderTime())
                .orderAmount(orders.getAmount())
                .build();
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        /*// 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.selectById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;*/

        //用户确认支付之后--假设已经支付成功，立即修改订单状态
        this.paySuccess(ordersPaymentDTO.getOrderNumber());
        return new OrderPaymentVO();
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = orderMapper.getByNumberAndUserId(outTradeNo, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);
    }

    /**
     * 再来一单
     * @param id
     */
    @Override
    public void again(Long id) {
        List<OrderDetail> orderDetails = orderDetailMapper.selectByOrderId(id);

        for (OrderDetail orderDetail : orderDetails) {
            /*if(orderDetail.getDishId() == null){
                Setmeal setmeal = setMealMapper.selectById(orderDetail.getSetmealId());
                if(setmeal.getStatus() == StatusConstant.DISABLE){
                    throw new OrderBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
                }
            }else {
                Dish dish = dishMapper.selectById(orderDetail.getDishId());
                if(dish.getStatus() == StatusConstant.DISABLE){
                    throw new OrderBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
                }
            }*/
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(orderDetail,shoppingCart,"id");
            shoppingCart.setUserId(BaseContext.getCurrentId());
            shoppingCartMapper.insert(shoppingCart);
        }
    }

    @Override
    public void deliveryOrder(Long id) {
        Orders orders = Orders.builder()
                .id(id)
                .status(Orders.DELIVERY_IN_PROGRESS)
                .build();
        orderMapper.update(orders);
    }

    @Override
    public void completeOrder(Long id) {
        Orders orders = Orders.builder()
                .id(id)
                .status(Orders.COMPLETED)
                .deliveryTime(LocalDateTime.now())
                .build();
        orderMapper.update(orders);
    }

    /**
     * 接单
     * @param ordersConfirmDTO
     */
    @Override
    public void confirmOrder(OrdersConfirmDTO ordersConfirmDTO) {
        //查询当前要接收的订单
        List<Orders> list = orderMapper.getOrderById(ordersConfirmDTO.getId());
        if (list == null || list.size() == 0){
            //订单不存在
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        Orders order = list.get(0);
        order.setStatus(Orders.CONFIRMED);
        //更新订单状态
        orderMapper.update(order);
    }

    /**
     * 拒单
     * @param ordersRejectionDTO
     */
    @Override
    public void rejectionOrder(OrdersRejectionDTO ordersRejectionDTO) {
        //查询当前要拒绝的订单
        List<Orders> list = orderMapper.getOrderById(ordersRejectionDTO.getId());
        if (list == null || list.size() == 0){
            //订单不存在
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        Orders order = list.get(0);
        order.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        order.setStatus(Orders.CANCELLED);
        //更新订单状态
        orderMapper.update(order);
    }

    /**
     * 取消订单
     * @param ordersCancelDTO
     */
    @Override
    public void cancelOrder(OrdersCancelDTO ordersCancelDTO) {
        //查询当前要取消的订单
        List<Orders> list = orderMapper.getOrderById(ordersCancelDTO.getId());
        if (list == null || list.size() == 0){
            //订单不存在
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        Orders order = list.get(0);
        if (order.getStatus()==Orders.PAID || order.getStatus() == Orders.COMPLETED ||order.getStatus()==Orders.CANCELLED){
            order.setCancelReason(ordersCancelDTO.getCancelReason());
            order.setStatus(Orders.CANCELLED);
            //更新订单状态
            orderMapper.update(order);
        }else {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

    }


    /**
     * 历史订单查询
     *
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult selectHistoryOrders(OrdersPageQueryDTO ordersPageQueryDTO) {
        //先使用插件
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        //Page<OrderVO> page = orderMapper.page2(ordersPageQueryDTO);
        Page<OrderVO> page = orderMapper.page(ordersPageQueryDTO);
        for (OrderVO orderVO : page) {
            List<OrderDetail> orderDetails = orderDetailMapper.selectByOrderId(orderVO.getId());
            orderVO.setOrderDetailList(orderDetails);
        }
        return new PageResult(page.getTotal(), page.getResult());
        /*List<Order> orderList = orderMapper.selectById(BaseContext.getCurrentId());
        for (int i = 0; i < orderList.size(); i++) {
            orderList.get(i).setOrderDetails(orderDetailMapper.selectByOrderId(orderList.get(i).getId()));
        }*/

        //return new PageResult(page.getTotal(),page.getResult()) ;
    }

    /**
     * 查看订单详细
     *
     * @param id
     */
    @Override
    public OrderVO selectOrderDetail(Long id) {
        OrderVO orderVO = new OrderVO();
        Order order = orderMapper.getByOrderId(id);
        BeanUtils.copyProperties(order, orderVO);
        List<OrderDetail> orderDetails = orderDetailMapper.selectByOrderId(id);
        orderVO.setOrderDetailList(orderDetails);
        return orderVO;
    }

    /**
     * 取消订单
     *
     * @param id
     */
    @Override
    @Transactional
    public void cancelOrder(long id) {
        Order order = orderMapper.getByOrderId(id);
        if (order.getStatus() == Order.PENDING_PAYMENT || order.getStatus() == Order.TO_BE_CONFIRMED) {
            orderMapper.cancelOrder(id, Order.CANCELLED);
        }else {
            throw new OrderBusinessException(MessageConstant.ORDER_BEGIN);
        }
    }

    /**
     * 订单搜索
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());

        Page<OrderVO> orderVOPage = orderMapper.conditionSearch(ordersPageQueryDTO);
        for (OrderVO orderVO : orderVOPage) {
            String name = "";
            List<OrderDetail> orderDetails = orderDetailMapper.selectByOrderId(orderVO.getId());
            for (OrderDetail orderDetail : orderDetails) {
                name += orderDetail.getName()+"-";
            }
            orderVO.setOrderDishes(name);
        }
        return new PageResult(orderVOPage.getTotal(),orderVOPage.getResult());
    }

    /**
     * 查看订单详情
     * @param id
     * @return
     */
    @Override
    public OrderVO ViewOrderDetail(Long id) {
        Orders orders = orderMapper.selectById2(id);

        List<OrderDetail> orderDetails = orderDetailMapper.selectByOrderId(id);

        String name = "";
        for (OrderDetail orderDetail : orderDetails) {
            name += orderDetail.getName();
        }

        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders,orderVO);
        orderVO.setOrderDetailList(orderDetails);
        orderVO.setOrderDishes(name);

        return orderVO;
    }

    /**
     * 各个状态订单数量
     * @return
     */
    @Override
    public OrderStatisticsVO statistics() {
        Integer toBeConfirmed = orderMapper.selectByStatus(Orders.TO_BE_CONFIRMED);
        Integer confirmed = orderMapper.selectByStatus(Orders.CONFIRMED);
        Integer deliveryInProgress = orderMapper.selectByStatus(Orders.DELIVERY_IN_PROGRESS);
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        return orderStatisticsVO;
    }

}
